const redisSessionStore = require('../lib/redisSessionStore');

module.exports = async function loginCheck(ctx, next) {
  if (!ctx.session.userInfo) {
    ctx.status = 401;
    ctx.body = {
      message: '用户尚未登录'
    };
    return;
  }

  const consistency = await redisSessionStore.userCookieCheck(ctx.session.externalKey, { ctx });
  if (!consistency) {
    ctx.status = 401;
    ctx.body = {
      message: '已在其他地方登录'
    };
    ctx.session = null;
    return;
  }

  await next();
};
